package cn.pink.common.support.tools.msg;

import cn.pink.common.proto.MsgIds;
import cn.pink.core.Chunk;
import cn.pink.core.Port;
import cn.pink.core.config.IronConfig;
import cn.pink.core.config.MsgFilterConfig;
import cn.pink.core.support.Log;
import cn.pink.core.support.SysException;
import com.google.protobuf.CodedInputStream;
import com.google.protobuf.GeneratedMessageV3;
import com.googlecode.protobuf.format.JsonFormat;

import java.io.IOException;
import java.util.Arrays;

/**
 * @Author: pink
 * @Date: 2022/7/4 14:29
 */
public class MsgTool {
    private static MsgTool tool = new MsgTool();

    private MsgTool() {

    }

    public static MsgTool getInstance() {
        return tool;
    }

    public static void init() {

    }

    /**
     * 打印协议
     */
    public void printMsg(int msgId, Chunk msgBuf) {
        if (!IronConfig.GATE_PRINT_MSG) {
            return;
        }

        //取出消息体
        CodedInputStream in = CodedInputStream.newInstance(msgBuf.buffer, msgBuf.offset, msgBuf.length);

        try {
            GeneratedMessageV3 msg = MsgIds.parseFrom(msgId, in);
            printMsg(msgId, msg);
        } catch (IOException e) {
            Log.error.error("MsgIds.parseFrom报错， msgId={}", msgId);
            throw new SysException(e);
        }
    }

    /**
     * 打印协议 full
     */
    public void printMsg(int msgId, GeneratedMessageV3 msg) {
        if (msg == null) {
            return;
        }

        if(Arrays.stream(MsgFilterConfig.values()).anyMatch(v -> v.name().equals(msg.getClass().getSimpleName()))) {
            return;
        }

        Port port = Port.getCurrent();

        Log.msg.info("{} print message: portId={}, msgId={}, content={}", port.getNodeId(), port.getId(), MsgIds.getNameById(msgId), JsonFormat.printToString(msg));
    }

    /**
     * 打印协议
     */
    public void printMsg(GeneratedMessageV3 msg) {
        if (msg == null) {
            return;
        }

        if(Arrays.stream(MsgFilterConfig.values()).anyMatch(v -> v.name().equals(msg.getClass().getSimpleName()))) {
            return;
        }


        Port port = Port.getCurrent();

        Log.msg.info("{} print message: portId={}, msgId={}", port.getNodeId(), port.getId(), msg.getClass().getSimpleName());
    }
}
